package cn.kennylee.codehub.common.das;

import org.springframework.lang.Nullable;

import java.util.EnumMap;
import java.util.Optional;

/**
 * DAS查询略工厂
 * <p>Created on 2024/12/11.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
public class DasStrategyFactory<E, T> {

    /**
     * 静态内部类，只有在第一次调用 getInstance 时才会加载
     */
    @SuppressWarnings({"rawtypes"})
    private static class SingletonHolder {
        private static final DasStrategyFactory INSTANCE = new DasStrategyFactory();
    }

    private final EnumMap<DasDbType, DasQueryStrategy<E, T>> strategyEnumMap;

    private DasStrategyFactory() {
        strategyEnumMap = new EnumMap<>(DasDbType.class);
    }

    /**
     * 全局访问点
     *
     * @return DasStrategyFactory
     */
    @SuppressWarnings({"rawtypes"})
    public static DasStrategyFactory getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 注册策略
     *
     * @param dbType   数据库类型
     * @param strategy 策略
     */
    public void registerStrategy(DasDbType dbType, DasQueryStrategy<E, T> strategy) {
        strategyEnumMap.put(dbType, strategy);
    }

    /**
     * 获取策略
     *
     * @param dbType 数据库类型
     * @return 策略
     */
    @Nullable
    public DasQueryStrategy<E, T> getStrategy(DasDbType dbType) {
        return Optional.ofNullable(strategyEnumMap.get(dbType)).map(DasQueryStrategy::newInstance).orElse(null);
    }

    /**
     * 查询策略是否存在
     */
    public boolean containsStrategy(DasDbType dbType) {
        return strategyEnumMap.containsKey(dbType);
    }

    /**
     * 删除策略
     */
    public void removeStrategy(DasDbType dbType) {
        strategyEnumMap.remove(dbType);
    }
}
